const qs = require('qs');
const handleBlogRouter = require("./src/router/blog");
const handleUserRouter = require("./src/router/user");
const { set, get } = require("./src/db/redis")
const { access } = require('./src/utils/log')

// // session 数据，全局数据，针对整个app
// const SESSION_DATA = {}

// 设置cookie的过期时间
const getCookieExpires = () => {
  const currenttime = new Date()
  // setTime 重新设置时间的函数； 将当前时间设置成了“当前时间+一天后”
  currenttime.setTime(currenttime.getTime() + 24 * 60 * 60 * 1000)
  console.log(":", currenttime.toUTCString())
  return currenttime.toUTCString()
}

// 处理postData
const getPostData = (req) => {
  const promise = new Promise((resolve, reject) => {
    if(req.method !== 'POST') {
      resolve({});
      return;
    } else {
      // console.log("小写出错", req.headers['content-type'], "大写出错", req.headers['Content-type'])
      if(req.headers['content-type'] !== "application/json") {
        resolve({});
        return;
      } else {
        let postData = '';
        req.on('data', chunk => {
          postData += chunk.toString();
        });
        req.on('end', () => {
          if(!postData) {
            resolve({});
            return;
          } else {
            resolve(
              JSON.parse(postData)
            )
          }
        });
      }
    }
  });
  return promise;
}

const serverHandler = (req, res) => {
  // 记录 access 日志
  access(`${req.method} -- ${req.url} -- ${req.headers['user-agent']} -- ${Date.now()}`)
  // 设置返回格式为 JSON
  res.setHeader('Content-type', 'application/json');
  // 获取path
  const url = req.url;
  req.path = url.split('?')[0];
  // 解析 query
  req.query = qs.parse(url.split('?')[1]);

  // 解析cookie
  req.cookie = {}
  const cookieStr = req.headers.cookie || ""  // k1=v1; k2=v2; k3=v3
  cookieStr.split(';').forEach(item => {
    if(!item) {
      return
    } else {
      const arrEle = item.split("=")
      const key = arrEle[0].trim()   // trim用于将cookie中的空格去掉
      const val = arrEle[1].trim()
      req.cookie[key] = val
    }
  });

  // // 解析session，即从cookie中获取userId，并且对应到session上
  // let needSetCookie =false
  // let userId = req.cookie.userid
  // if(userId) {
  //   if(!SESSION_DATA[userId]) {
  //     SESSION_DATA[userId] = {}
  //   }
  // } else {
  //   needSetCookie = true
  //   userId = `${Date.now()}_${Math.random()}`
  //   SESSION_DATA[userId] = {}
  // }
  // req.session = SESSION_DATA[userId]
  // console.log("app.js req.session: ", req.session)

  // 解析 session（使用 redis）
  let needSetCookie = false
  let userId = req.cookie.userid
  if(!userId) {
    needSetCookie = true
    userId = `${Date.now()}_${Math.random()}`
    // 初始化 redis 中的 session 值
    set(userId, {})
  }
  //  获取 session
  req.sessionId = userId
  get(req.sessionId).then(sessionData => {
    if(sessionData == null) {
      // 初始化 redis 中的 session 值
      set(userId, {})
      // 设置 session
      req.session = {}
    } else {
      // 设置 session
      req.session = sessionData
    }

    // 处理postData
    return getPostData(req)
  }).then(postData => {
    req.body = postData;
    const blogResult = handleBlogRouter(req, res);
    if(blogResult) {
      blogResult.then(blogData => {
        if(needSetCookie) {
          res.setHeader("Set-Cookie", `userid=${userId}; path=/; httpOnly; expires=${getCookieExpires()} `)
        }
        res.end(
          JSON.stringify(blogData)
        )
      })
      return;  // 如果blogResult有值的话，从这return掉，不要再继续
    }

    let userResult = handleUserRouter(req, res);
    if(userResult) {
      userResult.then(userData => {
        if(needSetCookie) {
          res.setHeader("Set-Cookie", `userid=${userId}; path=/; httpOnly; expires=${getCookieExpires()} `)
        }
        res.end(
          JSON.stringify(userData)
        )
      })
      return
    }
    // 未命中路由，返回404
    res.writeHead(404, {'Content-type': 'text/plain'});
    res.write('404 Not Found\n');
    res.end();
  })
}

module.exports = serverHandler;